<template>
  <!-- 选择发布账号 -->
  <template>
    <a-modal
      :visible="visible"
      title="选择账号"
      @cancel="closeModal"
      :width="1000"
    >
      <a-row :gutter="[16, 16]" class="content-box hide-scroller-bar">
        <!-- 分组 -->
        <a-col :span="7">
          <div class="mb">
            <a-input
              @change="handleGroupSearch"
              v-model:value="groupSearch"
              placeholder="分组名称"
              style="width: 150px; border-radius: 10px"
            />
          </div>
          <div class="mb">
            <a-checkbox
              v-if="groupList?.length || userCountList?.length"
              v-model:checked="isAllChecked"
              @change="checkedAllChange"
            >
              全部
            </a-checkbox>
          </div>
          <div class="mb" v-for="item in groupList" :key="item.id">
            <a-checkbox
              @change="GrouopItemCheck(item)"
              style="width: 100%"
              v-if="item.title"
              v-model:checked="item.checked"
            >
              {{ item.title }}
            </a-checkbox>
          </div>
        </a-col>
        <!-- 账号列表 -->
        <a-col :span="9">
          <div class="mb">
            <a-input
              @change="handleUserCountChange"
              v-model:value="userCountSearch"
              placeholder="账户名称"
              style="border-radius: 10px"
            />
          </div>
          <div class="mb" v-for="user in userCountList" :key="user.id">
            <a-space size="small">
              <a-checkbox
                @change="UserItemCheckd(user)"
                style="width: 100%"
                v-if="user?.platform_account_user?.nickname || user?.nickname"
                v-model:checked="user.checked"
              >
                {{ user?.platform_account_user?.nickname || user?.nickname }}
              </a-checkbox>
              <span
                class="status_tag"
                :style="{
                  color:
                    (user?.status_txt ||
                      user?.platform_account_user?.status_txt) == '离线'
                      ? 'red'
                      : '#389e0d',
                }"
                >{{
                  user?.status_txt || user?.platform_account_user?.status_txt
                }}</span
              >
              <a-tooltip>
                <template #title
                  >机构主号：{{
                    user?.user_expand_info?.parent_account?.nickname
                  }}</template
                >
                <a-tag
                  color="blue"
                  style="cursor: pointer; font-size: 8px !important"
                  v-if="
                    user?.user_expand_info?.account_type == 'org_sub' &&
                    user?.user_expand_info?.account_type_txt
                  "
                  >{{ user?.user_expand_info?.account_type_txt }}</a-tag
                >
              </a-tooltip>
              <a-tag
                color="purple"
                style="font-size: 8px !important"
                v-if="
                  user?.user_expand_info?.account_type == 'org_main' &&
                  user?.user_expand_info?.account_type_txt
                "
                >{{ user?.user_expand_info?.account_type_txt }}</a-tag
              >
              <a-tag
                style="font-size: 8px !important"
                v-if="
                  user?.user_expand_info?.account_type == 'default' &&
                  user?.user_expand_info?.account_type_txt
                "
                >{{ user?.user_expand_info?.account_type_txt }}</a-tag
              >
            </a-space>
          </div>
        </a-col>
        <a-col :span="8" v-if="checkCountList?.length">
          <div>已有账号:</div>
          <a-row
            v-for="(item, index) in checkCountList"
            :key="item.id"
            :gutter="[16, 16]"
            justify="space-between"
            class="user-list"
          >
            <a-col>
              <a-space size="small">
                <span>
                  {{ item?.nickname || item?.platform_account_user?.nickname }}
                </span>
                <span
                  class="status_tag"
                  :style="{
                    color:
                      (item?.status_txt ||
                        item?.platform_account_user?.status_txt) == '离线'
                        ? 'red'
                        : '#389e0d',
                  }"
                  >{{
                    item?.status_txt || item?.platform_account_user?.status_txt
                  }}</span
                >
                <a-tooltip>
                  <template #title
                    >机构主号：{{
                      item?.user_expand_info?.parent_account?.nickname
                    }}</template
                  >
                  <a-tag
                    color="blue"
                    style="cursor: pointer"
                    v-if="
                      item?.user_expand_info?.account_type == 'org_sub' &&
                      item?.user_expand_info?.account_type_txt
                    "
                    >{{ item?.user_expand_info?.account_type_txt }}</a-tag
                  >
                </a-tooltip>
                <a-tag
                  color="purple"
                  v-if="
                    item?.user_expand_info?.account_type == 'org_main' &&
                    item?.user_expand_info?.account_type_txt
                  "
                  >{{ item?.user_expand_info?.account_type_txt }}</a-tag
                >
                <a-tag
                  v-if="
                    item?.user_expand_info?.account_type == 'default' &&
                    item?.user_expand_info?.account_type_txt
                  "
                  >{{ item?.user_expand_info?.account_type_txt }}</a-tag
                >
              </a-space>
            </a-col>
            <a-col>
              <delete-outlined
                @click="userDeleteClick(item, index)"
                style="cursor: pointer"
              />
            </a-col>
          </a-row>
        </a-col>
      </a-row>

      <template #footer>
        <a-row justify="center">
          <a-col>
            <a-button
              type="primary"
              style="background: #2878ff; border: none; border-radius: 6px"
              @click="success"
            >
              保存
            </a-button>
          </a-col>
        </a-row>
      </template>
    </a-modal>
  </template>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { DeleteOutlined } from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import _ from "lodash";
export default defineComponent({
  name: "ChooseAccountModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    sourceType: {
      type: String,
      default: "",
    },
    filmVideoListLength: {
      type: Number,
      default: 0,
    },
    // 使用类型 -- 成片发布 或 其他地方
    useType: {
      type: String,
      default: '成片发布',
    }
  },
  components: { DeleteOutlined },
  setup(props, { emit }) {
    const state = reactive({
      groupSearch: "", //分组筛选字段
      userCountSearch: "", //账号列表筛选字段
      groupList: [], //分组列表
      userCountList: [], //账号列表
      isAllChecked: false,
      checkCountList: [], //选中账号列表
      searchGroupList: [], //分组筛选列表
      visible: false,
    });
    // 保存
    const success = () => {
      if (!state.checkCountList.length) {
        return message.warning("请选择账号");
      } else if (props.filmVideoListLength < state.checkCountList.length && (props.useType == '成片发布' || props.useType == '图集成片')) {
        return message.error("账号数量超出可发布成片上限");
      } else if (props.useType == '图片成片' && state.checkCountList.length > 1) {
        return message.error("图片成片只能选择一个账号");
      } else if (props.filmVideoListLength < state.checkCountList.length && props.useType == '图文任务') {
        return message.error("账号数量超出可发布图文上限");
      }
      // debugger
      let countList = state.checkCountList.map((item) => {
        if (item.platform_account_user) {
          return item.platform_account_user;
        } else {
          return item;
        }
      });
      console.log(countList,'countList');
      emit("onSuccess", JSON.parse(JSON.stringify(countList)));
      // state.visible = false;
      initData();
    };
    // 初始化数据
    const initData = () => {
      state.groupSearch = "";
      state.userCountSearch = "";
      state.groupList = [];
      state.userCountList = [];
      state.isAllChecked = false;
      state.checkCountList = [];
    };
    const showModal = (info) => {
      state.visible = true;
      getGroupList("init", info);
      state.checkCountList = info;
    };
    const getGroupList = (type, info) => {
      state.groupList = [];
      state.userCountList = [];
      state.isAllChecked = false;
      state.checkCountList = [];
      request
        .get("/work_ai", "/org/platformAccount/group/list", {
          source: props.sourceType,
          title: state.groupSearch,
          name: state.userCountSearch,
        })
        .then((res) => {
          //初始化分组列表
          state.groupList = res?.result;
          // 用户列表
          state.userCountList = res?.whole;
          state.groupList?.forEach((item) => {
            item.checked = false;
          });
          state.userCountList?.forEach((ele) => {
            ele.checked = false;
          });

          if (type == "init" && info && info.length) {
            // 回显单个账号勾选状态
            info.forEach((user) => {
              state.userCountList.forEach((rel) => {
                if (rel.id == user.id) {
                  rel.checked = true;
                }
              });
              groupCheck(user);
            });
            // 初始化分组状态

            // 同步全选按钮的勾选状态
            let isEveryUserCheck = state.userCountList?.every(
              (item) => item.checked
            );
            let isAllGroupCheck = state.groupList?.every(
              (item) => item.checked
            );
            // 根据账号列表的勾选状态，更新全选按钮的勾选状态
            state.isAllChecked =
              isEveryUserCheck && isAllGroupCheck ? true : false;
          }
        });
    };
    const RemoveDuplicates = (arr) => {
      const uniqueIds = []; // 用于存储已遇到的 ID
      const uniqueItems = []; // 用于存储去重后的数组
      arr.forEach((item) => {
        const id = item.platform_account_user
          ? item.platform_account_user?.id
          : item.id;
        if (!uniqueIds.includes(id)) {
          uniqueIds.push(id);
          uniqueItems.push(item);
        }
      });
      state.checkCountList = uniqueItems;
      return state.checkCountList;
    };
    // 全选
    const checkedAllChange = () => {
      // 同步账号勾选状态
      state.userCountList?.forEach((item) => {
        item.checked = state.isAllChecked;
      });
      // 同步分组全选
      state.groupList?.forEach((item) => {
        item.checked = state.isAllChecked;
      });
      state.checkCountList = state.isAllChecked
        ? RemoveDuplicates(JSON.parse(JSON.stringify(state.userCountList)))
        : [];
    };
    // 分组勾选
    const GrouopItemCheck = (item) => {
      let groupUserList = item?.platform_account_group_relation.map((item) => {
        return item.platform_account_user ? item.platform_account_user : item;
      }); //查找到对应的分组账号

      // 将分组下面的账号同步勾选状态
      if (groupUserList.length) {
        groupUserList.forEach((groupUser) => {
          state.userCountList.forEach((stateUser) => {
            if (groupUser.id == stateUser.id) {
              stateUser.checked = item.checked;
            }
          });
        });
      }
      // 同步全选按钮的勾选状态
      let isEveryUserCheck = state.userCountList?.every((item) => item.checked);
      let isAllGroupCheck = state.groupList?.every((item) => item.checked);
      // 根据账号列表的勾选状态，更新全选按钮的勾选状态
      state.isAllChecked = isEveryUserCheck && isAllGroupCheck ? true : false;
      // 更新选中列表
      state.checkCountList = RemoveDuplicates(
        JSON.parse(JSON.stringify(state.userCountList))?.filter(
          (item) => item.checked
        )
      );
    };
    // 同步分组勾选状态
    const groupCheck = (item) => {
      // 查找到选中项对应的父级列表
      state.groupList?.forEach((group) => {
        // 检查该分组是否与用户关联
        const isRelated = group.platform_account_group_relation.some(
          (relation) => {
            return relation.platform_account_user?.id === item.id;
          }
        );
        if (isRelated) {
          // 更新该分组的勾选状态
          const allChecked = group.platform_account_group_relation.every(
            (relation) => {
              const user = state.userCountList.find(
                (stateUser) =>
                  stateUser.id === relation.platform_account_user?.id
              );
              return user && user.checked;
            }
          );

          group.checked = allChecked;
        }
      });
    };
    // 账户单选
    const UserItemCheckd = (item) => {
      groupCheck(item);
      // 同步全选按钮的勾选状态
      let isEveryUserCheck = state.userCountList?.every((item) => item.checked);
      let isAllGroupCheck = state.groupList?.every((item) => item.checked);
      // 根据账号列表的勾选状态，更新全选按钮的勾选状态
      state.isAllChecked = isEveryUserCheck && isAllGroupCheck ? true : false;
      // 更新选中列表
      state.checkCountList = RemoveDuplicates(
        JSON.parse(JSON.stringify(state.userCountList))?.filter(
          (item) => item.checked
        )
      );
    };
    // 删除账号
    const userDeleteClick = (item, index) => {
      // 同步单选按钮状态
      let Index = state.userCountList.findIndex((ele) => ele.id === item.id);
      if (Index !== -1) {
        state.userCountList[Index].checked = false;
      }
      groupCheck(item);
      state.checkCountList.splice(index, 1); //更新选中列表
      // 同步全选按钮的勾选状态
      let isEveryUserCheck = state.userCountList?.every((item) => item.checked);
      let isAllGroupCheck = state.groupList?.every((item) => item.checked);
      // 根据账号列表的勾选状态，更新全选按钮的勾选状态
      state.isAllChecked = isEveryUserCheck && isAllGroupCheck ? true : false;
    };

    // 分组筛选
    const handleGroupSearch = _.debounce(() => {
      getGroupList();
    }, 500);
    // 账号筛选
    const handleUserCountChange = _.debounce(() => {
      getGroupList();
    }, 500);

    const closeModal = () => {
      state.visible = false;
    };
    return {
      ...toRefs(state),
      showModal,
      RemoveDuplicates,
      success,
      closeModal,
      checkedAllChange,
      GrouopItemCheck,
      UserItemCheckd,
      userDeleteClick,
      initData,
      handleGroupSearch,
      handleUserCountChange,
    };
  },
});
</script>

<style lang="less" scoped>
.mb {
  margin-bottom: 8px;
}

.user-list {
  margin: 5px 0;
}

.content-box {
  width: 100%;
  max-height: 600px;
  overflow: auto;
}
</style>
